package com.example.administrator.baseproject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import constants.HandlerConstant;
import customhandler.MyHandler;
import singleton.SingletonClass;
import utils.ActivityControl;
import utils.ToastUtil;

public abstract class RootActivity extends AppCompatActivity {
    protected FrameHandler mHandler;
    private MyHandler allHandler =SingletonClass.getSingleton(MyHandler.class);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new FrameHandler(this);
        ActivityControl.addActivity(this);

    }

    protected void sendEmptyMessage(int what) {
        mHandler.sendEmptyMessage(what);
    }

    protected void sendEmptyMessageDelay(int what, long delay) {
        mHandler.sendEmptyMessageDelayed(what, delay);
    }

    protected void sendMessage(Message msg) {
        mHandler.sendMessage(msg);
    }


    protected void onHandleMessage(Message msg) {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SingletonClass.getSingleton(MyHandler.class).unregistHandler(mHandler);
        ActivityControl.removeActivity(this);

//        Process proc = Runtime.getRuntime().exec(new String[]{
//                "am","startservice","-n","com.android.systemui/.SystemUIService"});
//        proc.waitFor();
    }



//    @Override
//    public void finish() {
//        super.finish();
//        SingletonClass.getSingleton(MyHandler.class).unregistHandler(mHandler);
//    }

    /**
     * 处理Activity上消息的Handler
     */
    protected static class FrameHandler extends Handler {

        private WeakReference<RootActivity> activityWrf;

        public FrameHandler(RootActivity activity) {
            activityWrf = new WeakReference<RootActivity>(activity);
            SingletonClass.getSingleton(MyHandler.class).registeHandler(this);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (activityWrf != null) {
//                Log.e("HH", "handleMessage:1 " );
                RootActivity activity = activityWrf.get();
                if (activity != null && !activity.isFinishing()) {
//                    Log.e("HH", "handleMessage:2 " );
                    try {
                        activity.onHandleMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
